<template>
	<view class="page-container">
		<view class="page-header">
			<view class="header-left">
				<text class="page-title">采购申请审批</text>
				<text class="page-subtitle">审核采购申请</text>
			</view>
			<view class="header-right">
				<button class="btn btn-default" @click="handleBack">返回</button>
			</view>
		</view>

		<view v-if="loading" class="loading-state">
			<text class="loading-text">加载中...</text>
		</view>

		<view v-else-if="!requestData" class="empty-state">
			<text class="empty-text">未找到采购申请信息</text>
		</view>

		<view v-else class="content-section">
			<!-- 申请信息 -->
			<view class="info-card">
				<view class="card-title">申请信息</view>
				<view class="info-row">
					<text class="info-label">采购类型：</text>
					<text class="type-badge" :class="'type-' + requestData.item_type">{{ getItemTypeText(requestData.item_type) }}</text>
				</view>
				<view class="info-row">
					<text class="info-label">采购物品：</text>
					<text class="info-value">{{ getItemName(requestData.item_id) }}</text>
				</view>
				<view class="info-row">
					<text class="info-label">申请数量：</text>
					<text class="info-value highlight">{{ requestData.requested_quantity || 0 }}</text>
				</view>
				<view class="info-row">
					<text class="info-label">申请人：</text>
					<text class="info-value">{{ getRequesterName(requestData.requester_info) }}</text>
				</view>
				<view class="info-row">
					<text class="info-label">紧急程度：</text>
					<text class="urgency-badge" :class="'urgency-' + requestData.urgency">{{ getUrgencyText(requestData.urgency) }}</text>
				</view>
				<view class="info-row">
					<text class="info-label">申请原因：</text>
					<text class="info-value">{{ requestData.reason || '暂无' }}</text>
				</view>
				<view class="info-row">
					<text class="info-label">申请日期：</text>
					<text class="info-value">{{ formatDate(requestData.create_time) }}</text>
				</view>
			</view>

			<!-- 审批操作 -->
			<view class="approve-card">
				<view class="card-title">审批操作</view>
				<view class="button-group">
					<button class="btn btn-approve" @click="handleApprove">批准</button>
					<button class="btn btn-reject" @click="handleReject">驳回</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'

const requestId = ref('')
const requestData = ref(null)
const loading = ref(false)

onLoad((options) => {
	if (options.id) {
		requestId.value = options.id
		loadData()
	}
})

async function loadData() {
	loading.value = true
	try {
		const dhPurchaseRequests = uniCloud.importObject('dh-purchase_requests')
		const result = await dhPurchaseRequests.getPurchaseRequestById(requestId.value)
		
		if (result.code === 200) {
			requestData.value = result.data
		} else {
			uni.showToast({ title: result.message || '加载失败', icon: 'error' })
		}
	} catch (error) {
		console.error('加载数据失败:', error)
		uni.showToast({ title: '加载数据失败', icon: 'error' })
	} finally {
		loading.value = false
	}
}

async function handleApprove() {
	uni.showModal({
		title: '确认批准',
		content: '确定要批准此采购申请吗？',
		success: async (res) => {
			if (res.confirm) {
				try {
					const dhPurchaseRequests = uniCloud.importObject('dh-purchase_requests')
					const userInfo = uni.getStorageSync('uni-id-pages-userInfo')
					const result = await dhPurchaseRequests.approvePurchaseRequest(
						requestId.value,
						userInfo._id,
						userInfo.nickname || userInfo.username
					)
					
					if (result.code === 200) {
						uni.showToast({ title: '批准成功', icon: 'success' })
						setTimeout(() => {
							uni.navigateBack()
						}, 1500)
					} else {
						uni.showToast({ title: result.message || '批准失败', icon: 'error' })
					}
				} catch (error) {
					console.error('批准失败:', error)
					uni.showToast({ title: '批准失败', icon: 'error' })
				}
			}
		}
	})
}

function handleReject() {
	uni.showModal({
		title: '驳回申请',
		content: '请输入驳回原因',
		editable: true,
		placeholderText: '请输入驳回原因',
		success: async (res) => {
			if (res.confirm) {
				const rejectionReason = res.content || '未填写驳回原因'
				try {
					const dhPurchaseRequests = uniCloud.importObject('dh-purchase_requests')
					const result = await dhPurchaseRequests.rejectPurchaseRequest(requestId.value, rejectionReason)
					
					if (result.code === 200) {
						uni.showToast({ title: '已驳回', icon: 'success' })
						setTimeout(() => {
							uni.navigateBack()
						}, 1500)
					} else {
						uni.showToast({ title: result.message || '驳回失败', icon: 'error' })
					}
				} catch (error) {
					console.error('驳回失败:', error)
					uni.showToast({ title: '驳回失败', icon: 'error' })
				}
			}
		}
	})
}

function getItemTypeText(itemType) {
	const typeMap = {
		1: '对外销售',
		2: '内部使用'
	}
	return typeMap[itemType] || '未知'
}

function getItemName(itemId) {
	if (!itemId) return '暂无'
	if (typeof itemId === 'object') {
		return itemId.item_name || itemId.product_name || '暂无'
	}
	return '暂无'
}

function getRequesterName(requesterInfo) {
	if (requesterInfo) {
		if (requesterInfo.real_name) return requesterInfo.real_name
		if (requesterInfo.nickname) return requesterInfo.nickname
		if (requesterInfo.username) return requesterInfo.username
	}
	return '未知用户'
}

function getUrgencyText(urgency) {
	const urgencyMap = {
		1: '普通',
		2: '加急',
		3: '紧急'
	}
	return urgencyMap[urgency] || '未知'
}

function formatDate(date) {
	if (!date) return '暂无'
	const d = new Date(date)
	return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
}

function handleBack() {
	uni.navigateBack()
}
</script>

<style scoped lang="scss">
.page-container {
	padding: 20px;
	background-color: #f5f7fa;
	min-height: 100vh;
}

.page-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 24px;
	background: white;
	padding: 20px;
	border-radius: 8px;
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.header-left {
	display: flex;
	flex-direction: column;
}

.page-title {
	font-size: 20px;
	font-weight: 600;
	color: #1f2937;
	margin-bottom: 4px;
}

.page-subtitle {
	font-size: 12px;
	color: #6b7280;
}

.btn {
	padding: 6px 14px;
	border-radius: 6px;
	border: none;
	cursor: pointer;
	font-size: 14px;
	font-weight: 500;
	transition: all 0.3s ease;

	&.btn-default {
		background-color: #e5e7eb;
		color: #374151;

		&:active {
			background-color: #d1d5db;
		}
	}

	&.btn-approve {
		background-color: #10b981;
		color: white;
		flex: 1;

		&:active {
			background-color: #059669;
		}
	}

	&.btn-reject {
		background-color: #ef4444;
		color: white;
		flex: 1;

		&:active {
			background-color: #dc2626;
		}
	}
}

.loading-state,
.empty-state {
	display: flex;
	justify-content: center;
	align-items: center;
	padding: 60px 20px;
	background: white;
	border-radius: 8px;
}

.loading-text,
.empty-text {
	font-size: 14px;
	color: #6b7280;
}

.content-section {
	display: flex;
	flex-direction: column;
	gap: 16px;
}

.info-card,
.approve-card {
	background: white;
	border-radius: 8px;
	padding: 20px;
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.card-title {
	font-size: 16px;
	font-weight: 600;
	color: #1f2937;
	margin-bottom: 16px;
	padding-bottom: 12px;
	border-bottom: 1px solid #e5e7eb;
}

.info-row {
	display: flex;
	align-items: center;
	padding: 12px 0;
	border-bottom: 1px solid #f3f4f6;

	&:last-child {
		border-bottom: none;
	}
}

.info-label {
	font-size: 14px;
	color: #6b7280;
	width: 100px;
	flex-shrink: 0;
}

.info-value {
	font-size: 14px;
	color: #1f2937;
	flex: 1;

	&.highlight {
		font-size: 18px;
		font-weight: 600;
		color: #3b82f6;
	}
}

.type-badge {
	display: inline-block;
	padding: 4px 10px;
	border-radius: 4px;
	font-size: 12px;
	font-weight: 600;

	&.type-1 {
		background-color: #dbeafe;
		color: #1e40af;
	}

	&.type-2 {
		background-color: #d1fae5;
		color: #065f46;
	}
}

.urgency-badge {
	display: inline-block;
	padding: 4px 12px;
	border-radius: 4px;
	font-size: 12px;
	font-weight: 600;

	&.urgency-1 {
		background-color: #e0e7ff;
		color: #3730a3;
	}

	&.urgency-2 {
		background-color: #fef3c7;
		color: #92400e;
	}

	&.urgency-3 {
		background-color: #fee2e2;
		color: #991b1b;
	}
}

.button-group {
	display: flex;
	gap: 12px;
}
</style>

